package com.example.sportjava.controller;

import com.alibaba.fastjson.JSON;
import com.example.sportjava.bean.QueryInfo;
import com.example.sportjava.bean.User;
import com.example.sportjava.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Queue;

@RestController
public class UserController {

    @Autowired
    private UserDao udao;
    @RequestMapping("/allUser")
    public String getUserList(QueryInfo queryInfo){
        //获取最大列表数和当前编号
        int userCounts = udao.getUserCounts( "%" + queryInfo.getQuery() + "%");
        int pageNum = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();

        List<User> users = udao.getAllUser("%" + queryInfo.getQuery() + "%" ,pageNum ,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("userCounts" ,userCounts);
        res.put("data" ,users);
        System.out.println("总条数" + userCounts);
        String users_JSON = JSON.toJSONString(res);
        return users_JSON;

    };
    @RequestMapping("/userState")
    public String updateState(@RequestParam("id")Integer id,
                              @RequestParam("state")Boolean state){
        int i = udao.updateState(id ,state);
        return i > 0 ? "success":"error";
    } ;

    @RequestMapping("/addUser")
    public String addUser(@RequestBody User user){
      user.setRole("普通用户");
      user.setState(false);
      int i = udao.addUser(user);
      return i > 0 ? "success":"error";
    };

    @RequestMapping("/deleteUser")
    public String deleteUser(int id){
        int i = udao.deleteUser(id);
        return i > 0 ? "success":"error";
    };
    @RequestMapping("/getUpdate")
    public String getUpdateUser(int id){
        System.out.println("编号:"+id);
        User updateUser = udao.getUpdateUser(id);
        String users_json = JSON.toJSONString(updateUser);
        return users_json;
    };

    @RequestMapping("/editUser")
    public String editUser(@RequestBody User user){
        System.out.println(user);
        int i = udao.editUser(user);
        return i > 0? "success":"error";
    };
    @RequestMapping("/changeRole")
    public String changeUserRole(@RequestBody User user){
        System.out.println(user);
        int i = udao.changeUserRole(user);
        return i > 0? "success":"error";
    };
}
